package Game.AI 
{
	import Box2D.Dynamics.b2ContactListener;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.geom.Point;
	import flash.utils.Timer;
	import Game.GameElements.GameObject;
	import Game.GameElements.Tank;
	/**
	 * ...
	 * @author Yevgeniy Logachev
	 */
	public class EnemyTankAI 
	{
		public static const EASY:int 		= 0;
		public static const MEDIUM:int 		= 1;
		public static const HARD:int 		= 2;
		
		private var m_radiusVisiblity:int 	= 0;
		private var m_targetPosition:Point 	= null;
		
		private var m_tank:Tank 			= null;
		
		private var m_timer:Timer 			= null;
		private var m_updateTime:int 		= 0;
		
		private var m_difficulty:int 		= 0;
		
		public function EnemyTankAI(enemyTank:Tank, difficulty:int) 
		{
			m_difficulty = difficulty;
			switch(difficulty)
			{
				case EASY:
					m_radiusVisiblity = 50;
					m_updateTime = 1500;
				break;
				
				case MEDIUM:
					m_radiusVisiblity = 150;
					m_updateTime = 1300;
				break;
				
				case HARD:
					m_radiusVisiblity = 200;
					m_updateTime = 500;
				break;
			}
			
			m_tank = enemyTank;
			m_targetPosition = new Point(100, 100);
			m_tank.graphics.lineStyle(3, 0x00FFFF);
			
			
			m_timer = new Timer(m_updateTime);
			m_timer.addEventListener(TimerEvent.TIMER, updateAction);
			m_timer.start();
		}
		
		public function getTank():Tank
		{
			return m_tank;
		}
		
		public function get difficulty():int
		{
			return m_difficulty;
		}
		
		public function freeze():void
		{
			if (m_timer)
			{
				m_timer.stop();
			}
		}
		
		public function unfreeze():void
		{
			if (m_timer)
			{
				m_timer.start();
			}
		}
		
		public function release():void
		{
			m_tank = null;
			m_timer.removeEventListener(TimerEvent.TIMER, updateAction);
			m_timer = null;
		}
		
		public function updateAction(e:TimerEvent):void
		{
			for each(var tank:GameObject in GameObject.gameObjects)
			{
				if (tank is Tank && tank != m_tank)
				{
					if (Point.distance(new Point(m_tank.x, m_tank.y), new Point(tank.x, tank.y)) < m_radiusVisiblity)
					{
						rotateToTarget(new Point(tank.x, tank.y));
						m_tank.doRocket();
						return;
					}
				}
			}
			
			m_tank.setDirection = int(Math.random() * 4) + 1;
			
			if (Math.random() > 0.8)
			{
				m_tank.doRocket();
			}
		}
		
		public function rotateToTarget(target:Point):void
		{
			var dx:int = m_tank.x - target.x;
			var dy:int = m_tank.y - target.y;
			
			if (Math.abs.apply(null, [dx]) > Math.abs.apply(null, [dy]))
			{
				m_tank.setDirection = (dx > 0) ? Tank.DIRECTION_LEFT : Tank.DIRECTION_RIGHT;
			}
			else
			{
				m_tank.setDirection = (dy > 0) ? Tank.DIRECTION_UP : Tank.DIRECTION_DOWN;
			}
		}
		
		public function update():void
		{
			m_tank.moveTo(m_tank.getDirection);
		}
	}

}